//
//  logincontroll.m
//  MBObjectServer
//
//  Created by admin on 3/31/14.
//  Copyright (c) 2014 MBpayer. All rights reserved.
//

#import "logincontroll.h"
#import "EPOSPars.h"
#import "FileManger.h"
#import "Headertest.h"

@implementation logincontroll

@synthesize baseserver;

@synthesize cacheDic;

-(id)init{
    self=[super init];
    if (!self) {
        return nil;
    }
    baseserver = [[MBBaseServer alloc]init];

    return self;
}

//登录接口
-(void)LoginCheck:(NSString *)orgecode
         withName:(NSString *)name
         withpwd:(NSString *)pwd
         block:(void (^)(id))processResult{
    
    
    EPOSPars *parsDic = [[EPOSPars alloc]init];
    parsDic.OrgCode = orgecode;
    parsDic.UserID = name;
    parsDic.UserPwd = pwd;
    NSMutableDictionary *parsDictionary = [[NSMutableDictionary alloc]init];
    parsDictionary = [EPOSPars getDictionaryFromEPOSPars:parsDic];
    __weak logincontroll *weakSelf = self;
    [self.baseserver setRequestStyle:nil andSetPathString:@"sysuser_handler.ashx" andSetHeadString:nil andActionName:@"LoginCheck" andSetMainDictionary:parsDictionary block:^(id json) {
        NSDictionary * dic  = (NSDictionary *)json;
        //这里做下数据处理
        BOOL  Result = [[dic objectForKey:@"Result"] boolValue];
        
        if (!Result) {
            NSString * ErrMessage = [dic objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alertview show];
            
        }
        else{
            
            weakSelf.cacheDic = [[NSDictionary alloc] init];
            weakSelf.cacheDic = dic;
            
            
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            NSNumber * cashteamid = [userDefaults objectForKey:kCashierTeamID];
            if ([cashteamid intValue]== 0) {
                [weakSelf saveUserDefault:weakSelf.cacheDic];
                [weakSelf ondutywork:name block:^(id json) {
                    NSNumber * result = (NSNumber *)json;
                    processResult(result);
                }];
                
            }else{
                //调用获取当前钱箱用户
                [weakSelf GetNowCashierUser:^(NSString *responseData) {
                    //返回的用户信息如果和当前保存用户信息一直则正常登录否则先交班再登录
                    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
                    NSString * localUserid = [userDefaults objectForKey:kUserID];
                    if ([responseData isEqualToString:localUserid]) {
                        //登录成功
                        processResult([dic objectForKey:@"Result"]);
                 

                    }else{

//
//                        [weakSelf ondutywork:name block:^(id json) {
//                            
//                            NSNumber * result = (NSNumber *)json;
//                            
//                            processResult(result);
//                        }];
//先交班再执行当班过程
                        [weakSelf offDutyFlow:^(id json) {
//                            BOOL  Result = [(NSNumber *)json boolValue];
                            [weakSelf ondutywork:name block:^(id json) {
                                
                                NSNumber * result = (NSNumber *)json;
                                
                                processResult(result);
                            }];
                        }];
                    }
                }];
                
            }
        }
        
        
    } failblock:^(NSError *error) {
        
        [SVProgressHUD showErrorWithStatus:error.description];
        
    }];
}
#pragma mark 交班(OffDutyFlow)
-(void)offDutyFlow:(void(^)(id json))processResult{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * cashboxdic = [[NSMutableDictionary alloc] init];
    NSNumber * casherTeamId = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashierTeamID] intValue]];
    NSNumber * cashierid = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashierID] intValue]];
    NSNumber * cashvalue = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashSale] intValue]];
    NSNumber * cardvalue = [NSNumber numberWithInt:[[userDefaults objectForKey:kCardSale] intValue]];
    NSNumber * VoucherValue = [NSNumber numberWithInt:[[userDefaults objectForKey:kVoucherSale] intValue]];
    NSNumber * CashVoucherValue = [NSNumber numberWithInt:[[userDefaults objectForKey:kVoucher2Sale] intValue]];
    NSNumber * OtherValue = [NSNumber numberWithInt:[[userDefaults objectForKey:kOtherSale] intValue]];
    NSNumber * Memo = [NSNumber numberWithInt:[[userDefaults objectForKey:kSumTotal] intValue]];
    
    [cashboxdic setObject:[userDefaults objectForKey:kOrgCode] forKey:kOrgCode];
    [cashboxdic setObject:cashierid forKey:kCashierID];
    [cashboxdic setObject:casherTeamId forKey:kCashierTeamID];
    [cashboxdic setObject:cashvalue forKey:@"CashValue"];
    [cashboxdic setObject:cardvalue forKey:@"CardValue"];
    [cashboxdic setObject:VoucherValue forKey:@"VoucherValue"];
    [cashboxdic setObject:CashVoucherValue forKey:@"CashVoucherValue"];
    [cashboxdic setObject:OtherValue forKey:@"OtherValue"];
    [cashboxdic setObject:Memo forKey:@"Memo"];
    [self.baseserver setRequestStyle:nil andSetPathString:@"cashbox_handler.ashx" andSetHeadString:nil andActionName:@"OffDutyFlow" andSetMainDictionary:cashboxdic block:^(NSDictionary *responseData) {
        NSDictionary * dic = responseData;
        BOOL  Result = [[dic objectForKey:@"Result"] boolValue];
        if (!Result) {
            NSString * ErrMessage = [dic objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        else{
            processResult([dic objectForKey:@"Result"]);
        }
    } failblock:^(NSError *error) {
        
    }];
}

-(void)ondutywork:(NSString *)userid block:(void(^)(id json))processResult{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * cashboxdic = [[NSMutableDictionary alloc] init];
    
    NSNumber * casherid = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashierID] intValue]];
    NSNumber * cashcode = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashCode] intValue]];
    
    
    [cashboxdic setObject:[userDefaults objectForKey:kOrgCode] forKey:kOrgCode];
    [cashboxdic setObject:userid forKey:kUserID];
    [cashboxdic setObject:casherid forKey:kCashierID];
    [cashboxdic setObject:cashcode forKey:kCashCode];
    __weak logincontroll *weakSelf = self;
    [self.baseserver setRequestStyle:nil andSetPathString:@"cashbox_handler.ashx" andSetHeadString:nil andActionName:@"OnDutyFlow" andSetMainDictionary:cashboxdic block:^(NSDictionary *responseData) {
        NSDictionary * dic = responseData;
        NSNumber * result = (NSNumber *)[dic objectForKey:@"Result"];
        BOOL  Result = [[dic objectForKey:@"Result"] boolValue];
        if (!Result) {
            NSString * ErrMessage = [dic objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        else{

            [weakSelf saveSetDuty:dic];
            
            processResult(result);
        }

    } failblock:^(NSError *error) {
        
    }];
}

#pragma mark 获取当前当班人员(GetNowCashierUser)
-(void)GetNowCashierUser:(void(^)(NSString * responseData))processResult{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * cashboxdic = [[NSMutableDictionary alloc] init];
    NSNumber * casherid = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashierID] intValue]];
    NSNumber * casherTeamId = [NSNumber numberWithInt:[[userDefaults objectForKey:kCashierTeamID] intValue]];
    
    [cashboxdic setObject:[userDefaults objectForKey:kOrgCode] forKey:kOrgCode];
    [cashboxdic setObject:casherid forKey:kCashierID];
    [cashboxdic setObject:casherTeamId forKey:kCashierTeamID];
    __block NSString * cashieruserid;
    [self.baseserver setRequestStyle:nil andSetPathString:@"cashbox_handler.ashx" andSetHeadString:nil andActionName:@"GetNowCashierUser" andSetMainDictionary:cashboxdic block:^(NSDictionary *responseData) {
        NSDictionary * dic = responseData;
        BOOL  Result = [[dic objectForKey:@"Result"] boolValue];
        if (!Result) {
            NSString * ErrMessage = [dic objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];

            [alertview show];
        }
        else{
            cashieruserid = [dic objectForKey:@"CashierUserID"];
            processResult(cashieruserid);
        }
        
    } failblock:^(NSError *error) {
        
    }];

}


#pragma mark 初始化钱箱
-(void)GetCodeByAddressByOrgeCode:(NSString *)orgecodes{
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:orgecodes forKey:kOrgCode];
    [userDefaults synchronize];
    NSString * imei = [userDefaults objectForKey:kIMEI];
    NSMutableDictionary * cashboxdic = [[NSMutableDictionary alloc] init];
    [cashboxdic setObject:orgecodes forKey:kOrgCode];
    [cashboxdic setObject:imei forKey:kIMEI];
    
    NSNumber * IsTestMode = [NSNumber numberWithBool:FALSE];
    [cashboxdic setObject:IsTestMode forKey:@"IsTestMode"];
    __weak logincontroll *weakSelf = self;
    [self.baseserver setRequestStyle:nil andSetPathString:@"cashbox_handler.ashx" andSetHeadString:nil andActionName:@"GetCodeByAddress" andSetMainDictionary:cashboxdic block:^(NSDictionary *responseData) {

        //这里做下数据处理
        BOOL  Result = [[responseData objectForKey:@"Result"] boolValue];
        
        if (!Result) {
            NSString * ErrMessage = [responseData objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            
            [alertview show];
            
        }
        else{
            FileManger * fm = [[FileManger alloc] init];
            [fm deleteFile:fLog withDir:fLog];
            
            [weakSelf saveIMEI:responseData];
        }
    } failblock:^(NSError *error) {
        
    }];
}
-(void)RetrieveContainers:(NSString *)orgecode withName:(NSString *)name withpwd:(NSString *)pwd{
    EPOSPars *parsDic = [[EPOSPars alloc]init];
    //            parsDic.OrgCode = @"A01339S011";
    parsDic.OrgCode = orgecode;
    parsDic.UserID = [name uppercaseString];
    parsDic.UserPwd = pwd;
    NSMutableDictionary *parsDictionary = [[NSMutableDictionary alloc]init];
    parsDictionary = [EPOSPars getDictionaryFromEPOSPars:parsDic];
    __weak logincontroll *weakSelf = self;
    [self.baseserver setRequestStyle:nil andSetPathString:@"container_handler.ashx" andSetHeadString:nil andActionName:@"RetrieveContainers" andSetMainDictionary:parsDictionary block:^(NSDictionary *responseData) {
        NSDictionary * dic = responseData;
        BOOL  Result = [[dic objectForKey:@"Result"] boolValue];
        if (!Result) {
            NSString * ErrMessage = [dic objectForKey:@"ErrMessage"];
            UIAlertView * alertview = [[UIAlertView alloc] initWithTitle:@"错误" message:ErrMessage delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertview show];
        }
        else{
            NSArray * ContainsArray = [dic objectForKey:@"Contains"];
            
            [weakSelf cacheContainers:ContainsArray];
        }

    } failblock:^(NSError *error) {
        
    }];
}
#pragma mark 缓存货位信息
-(void)cacheContainers:(NSArray * )array{
    FileManger * fm = [[FileManger alloc] init];
    [fm writeFile:fContainers withDir:fContainers WithContentArray:array];
}
#pragma mark /保存用户数据
//保存用户数据
-(void)saveUserDefault:(NSDictionary *)dic{
    
    NSArray * SysUsers_array = [dic objectForKey:@"SysUsers"];
    //    只取第一个  为有效数据
    NSDictionary * SysUsers_dic = [SysUsers_array objectAtIndex:0];
    NSArray * Shops_array = [dic objectForKey:@"Shops"];
    //    只取第一个  为有效数据
    NSDictionary * Shops_dic = [Shops_array objectAtIndex:0];
    
    
    //将上述数据全部存储到NSUserDefaults中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //
    [userDefaults setObject:[SysUsers_dic objectForKey:kOrgCode] forKey:kOrgCode];
    [userDefaults setObject:[SysUsers_dic objectForKey:kUserID] forKey:kUserID];
    [userDefaults setObject:[SysUsers_dic objectForKey:kOwnerOrgCode] forKey:kOwnerOrgCode];
    MBLog(@"+%@",[SysUsers_dic objectForKey:kOwnerOrgCode]);
    [userDefaults setObject:[SysUsers_dic objectForKey:kUserName] forKey:kUserName];
    
    [userDefaults setObject:[Shops_dic objectForKey:kShopName] forKey:kShopName];
    MBLog(@"%@",[userDefaults stringForKey:kUserName]);
    [userDefaults synchronize];
}
#pragma mark 设置当班 记录设置之后的值
-(void)saveSetDuty:(NSDictionary *)dic{
    //将上述数据全部存储到NSUserDefaults中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //
    //    [userDefaults setObject:[dic objectForKey:kUserID] forKey:kUserID];
    [userDefaults setObject:[dic objectForKey:kCashierID] forKey:kCashierID];
    [userDefaults setObject:[dic objectForKey:kCashierTeamID] forKey:kCashierTeamID];
    
    [userDefaults synchronize];
}
#pragma mark //记录|终端机器码(IMEI)
-(void)saveIMEI:(NSDictionary *)dic{
    //将上述数据全部存储到NSUserDefaults中
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //
    [userDefaults setObject:[dic objectForKey:kCashCode] forKey:kCashCode];
    [userDefaults setObject:[dic objectForKey:kCashierID] forKey:kCashierID];
    
    [userDefaults setObject:[dic objectForKey:kCashierTeamID] forKey:kCashierTeamID];
    
    MBLog(@"%@ %d %d",[dic objectForKey:kCashCode],[[dic objectForKey:kCashierID] intValue],[[dic objectForKey:kCashierTeamID] intValue]);
    [userDefaults synchronize];
}

-(void)dealloc{
    self.baseserver.baseclient=nil;
    self.baseserver=nil;
}
@end
